'use client';

import React, { useCallback, useRef, useState } from 'react';
import toast from 'react-hot-toast';

export interface ConfirmButtonProps {
  title?: string;
  content: React.ReactNode;
  children: React.ReactNode;
  /**
   * 确认按钮的文本
   */
  confirmText?: string;
  /**
   * 自定义操作按钮
   */
  actions?: React.ReactNode[];
  onConfirm?: () => void | Promise<void>;
}

function ConfirmNoMemoized(props: ConfirmButtonProps) {
  const { title, content, children, confirmText = '确定', actions, onConfirm } = props;

  const [confirming, setConfirming] = useState(false);

  const dialogRef = useRef<HTMLDialogElement>(null);

  const closeDialog = useCallback(() => {
    if (dialogRef.current) {
      dialogRef.current.close();
      document.documentElement.style.removeProperty('scrollbar-gutter'); // 关闭对话框时移除样式
    }
  }, []);

  const openDialog = useCallback(() => {
    if (dialogRef.current) {
      // 不要用 showModal，否则会导致 dialog 被标为 top-layer 永远置为最上层, 任何元素都无法覆盖该元素
      dialogRef.current.show();
      // 禁用 daisyui 的 scrollbar-gutter 样式，否则右侧会出现滚动条占位区域
      document.documentElement.style.setProperty('scrollbar-gutter', 'auto');
    }
  }, []);

  return (
    <>
      {React.Children.map(children, (child) => {
        if (
          React.isValidElement<{ onClick?: React.MouseEventHandler }>(child) &&
          typeof child.props.onClick === 'function'
        ) {
          // 如果原本有 onClick，合并调用
          return React.cloneElement(child, {
            onClick: (e: React.MouseEvent) => {
              child.props.onClick?.(e);
              openDialog();
            },
          });
        }
        if (React.isValidElement<{ onClick?: React.MouseEventHandler }>(child)) {
          // 没有 onClick 直接加
          return React.cloneElement(child, {
            onClick: () => {
              openDialog();
            },
          });
        }
        return child;
      })}
      <dialog ref={dialogRef} className="modal">
        <div className="modal-box">
          {title && <h3 className="font-bold text-lg">{title}</h3>}
          <div className="py-4">{content}</div>
          <div className="modal-action">
            {!actions && (
              <button
                className="btn btn-primary rounded-full"
                disabled={confirming}
                onClick={() => {
                  setConfirming(true);
                  const cb = onConfirm?.();
                  if (cb instanceof Promise) {
                    cb.then(() => {
                      // 操作成功后关闭对话框
                      setConfirming(false);
                      closeDialog();
                    }).catch((err) => {
                      // 操作失败后提示错误
                      setConfirming(false);
                      toast.error((err as Error).message || '确认失败');
                    });
                    return;
                  }
                  setConfirming(false);
                  closeDialog();
                }}
              >
                {confirming && <span className="loading loading-spinner loading-sm" />}
                {confirmText}
              </button>
            )}
            <div className="flex items-center gap-2 justify-end">{actions}</div>
          </div>
        </div>
      </dialog>
    </>
  );
}

export const Confirm = React.memo(ConfirmNoMemoized);
